package com.foreknow.service.impl;

import com.foreknow.bean.Admin;
import com.foreknow.dao.AdminDao;
import com.foreknow.dao.impl.AdminDaoImpl;
import com.foreknow.db.DBManager;
import com.foreknow.service.AdminService;

import java.sql.Connection;
import java.sql.SQLException;

public class AdminServiceImpl implements AdminService {

  @Override
  public Admin isValidate(String username, String password) {
        //连接数据库
        DBManager dbManager = DBManager.getInstance();
        //调用连接数据库的方法
        Connection conn = dbManager.getConnection();
        //创建dao层的对象
        AdminDaoImpl adminDao = new AdminDaoImpl();
        //调用AdminDaoImpl对象中的 public void setConnection(Connection connection)方法连接数据库
        adminDao.setConnection(conn);
        Admin admin = null;
        try {
          admin = adminDao.isCheckLogin(username,password);
        } catch (SQLException e) {
          e.printStackTrace();
        }
        return admin;
      }

      @Override
      public boolean add(Admin admin) {
        //连接数据库
        DBManager dbManager = DBManager.getInstance();
        //调用连接数据库的方法
        Connection conn = dbManager.getConnection();
        //创建dao层的对象
        AdminDaoImpl adminDao = new AdminDaoImpl();
        //调用AdminDaoImpl对象中的 public void setConnection(Connection connection)方法连接数据库
        adminDao.setConnection(conn);
        boolean isRight = false;
        try {
          //调用dao层的添加方法，因为抛出了SQLException异常，所以要处理它。
          isRight = adminDao.save(admin);
          //手动提交事物，添加到数据库中的数据才会真实在存在
          conn.commit();
    } catch (SQLException e) {
      try {
        //回滚事物，取消之前的操作
        conn.rollback();
      } catch (SQLException ex) {
        ex.printStackTrace();
      }
      e.printStackTrace();
    }
    return isRight;
  }

  public static void main(String[] args) {
    AdminService service = new AdminServiceImpl();
    Admin admin = new Admin();
    admin.setUsername("blues");
    admin.setPassword("111111");
    admin.setAge(50);
    admin.setSchool("foreknow");
    //调用业务层的添加方法
    boolean isRight = service.add(admin);
    if(isRight) {
      System.out.println("添加成功......");
    }else {
      System.out.println("添加失败......");
    }

//    Admin admin = service.isValidate("tom","123456");
//    if(admin!=null){
//      System.out.println(admin.getUsername());
//    }else {
//      System.out.println("此数据没有查询到！！！！！！");
//    }
  }

}
